package com.yuqing.sentimentapp.workspace.search;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkface.baselibrary.utils.AppManager;
import com.linkface.baselibrary.utils.DateUtil;
import com.linkface.baselibrary.utils.LogUtil;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.workspace.search.entity.CityResult;
import com.yuqing.sentimentapp.workspace.search.entity.RegionResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DateTimePicker;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by shenhe on 2020/4/20.
 */
public class YqSearchActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.et_keyword)
    EditText mEtKeyword;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.ll_start_time)
    LinearLayout mLlStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.ll_end_time)
    LinearLayout mLlEndTime;
    @BindView(R.id.et_source)
    EditText mEtSource;
    @BindView(R.id.tv_region)
    TextView mTvRegion;
    @BindView(R.id.ll_region)
    LinearLayout mLlRegion;
    @BindView(R.id.tv_search)
    TextView mTvSearch;
    @BindView(R.id.tv_city)
    TextView mTvCity;
    @BindView(R.id.ll_city)
    LinearLayout mLlCity;
    private List<RegionResult.DataBean.RegionsBean> regions = new ArrayList<>();
    private List<CityResult.DataBean> cityList = new ArrayList<>();
    private String deptLevel;

    public static void goActivity(Activity activity) {
        Intent intent = new Intent(activity, YqSearchActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_yq_search;
    }

    @Override
    public void initPresenter() {
        LoginResultBean.DataBean.UserBean user = SharePrefrenceHelper.getUser();
        if (user != null && user.getDeptVo() != null) {
            deptLevel = user.getDeptVo().getDeptLevel();
        }
        getRegionResult();
    }

    private void getSubRegion(String regionCode) {
        ModuleManager.getInstance().getSearchSubRegionResult(regionCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<CityResult>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    protected void onSuccess(CityResult cityResult) {
                        if (cityResult == null) return;
                        cityList.clear();
                        CityResult.DataBean elementCity = new CityResult.DataBean();
                        elementCity.setName("请选择");
                        cityList.add(0, elementCity);
                        if (cityResult.getData() == null) return;
                        cityList.addAll(cityResult.getData());
                    }

                    @Override
                    protected void onFailure(String message) {

                    }
                });
    }

    private void getRegionResult() {
        ModuleManager.getInstance().getSearchPreResult()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<RegionResult>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    protected void onSuccess(RegionResult regionResult) {
                        if (regionResult == null) return;
                        regions.clear();
                        RegionResult.DataBean.RegionsBean element = new RegionResult.DataBean.RegionsBean();
                        element.setName("请选择");
                        regions.add(0, element);
                        RegionResult.DataBean data = regionResult.getData();
                        if (data == null || data.getRegions() == null) return;
                        regions.addAll(data.getRegions());
                    }

                    @Override
                    protected void onFailure(String message) {
                        LogUtil.e("shenhe_yuqinglog=" + message);
                    }
                });
    }

    @Override
    public void initView() {
        if (TextUtils.isEmpty(deptLevel)) return;
        /**
         * 支队隐藏二级地域
         */
        if (TextUtils.equals(deptLevel, "2")) {
            mLlCity.setVisibility(View.GONE);
        } else {
            mLlCity.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.iv_back, R.id.ll_start_time, R.id.ll_end_time, R.id.ll_region, R.id.tv_search, R.id.ll_city})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_start_time:
                showTimeSelectorView(0);
                break;
            case R.id.ll_end_time:
                showTimeSelectorView(1);
                break;
            case R.id.ll_region:
                if (regions == null || regions.size() == 0) return;
                PopupMenu popupMenu = new PopupMenu(this, mLlRegion);
                Menu menu_more = popupMenu.getMenu();
                for (int i = 0; i < regions.size(); i++) {
                    menu_more.add(Menu.NONE, i, i, regions.get(i).getName());
                }
                popupMenu.setOnMenuItemClickListener(menuItem -> {
                    int i = menuItem.getItemId();
                    mTvRegion.setText(regions.get(i).getName());
                    mTvRegion.setTag(regions.get(i).getCode());

                    if (TextUtils.isEmpty(regions.get(i).getCode())) {
                        return true;
                    }
                    /**
                     * 请求二级地域，市
                     */
                    getSubRegion(regions.get(i).getCode());
                    return true;
                });
                popupMenu.show();
                break;
            case R.id.ll_city:
                if (cityList == null || cityList.size() == 0) return;
                PopupMenu popupMenuCity = new PopupMenu(this, mLlRegion);
                Menu menu_more_city = popupMenuCity.getMenu();
                for (int i = 0; i < cityList.size(); i++) {
                    menu_more_city.add(Menu.NONE, i, i, cityList.get(i).getName());
                }
                popupMenuCity.setOnMenuItemClickListener(menuItem -> {
                    int i = menuItem.getItemId();
                    mTvCity.setText(cityList.get(i).getName());
                    mTvCity.setTag(cityList.get(i).getCode());
                    return true;
                });
                popupMenuCity.show();
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(mTvStartTime.getText().toString())) {
                    showShortToast("请选择开始时间");
                    return;
                }
                String from = TextUtils.isEmpty(mTvStartTime.getText().toString()) ? "" : mTvStartTime.getText().toString();
                String to = TextUtils.isEmpty(mTvEndTime.getText().toString()) ? "" : mTvEndTime.getText().toString();

                /**
                 * 支队时：region = ""，city = mTvRegion.getTag().toString()
                 */
                String region = "";
                String city = "";
                if (TextUtils.equals(deptLevel, "2")) {
                    city = mTvRegion.getTag() == null ? "" : mTvRegion.getTag().toString();
                } else {
                    region = mTvRegion.getTag() == null ? "" : mTvRegion.getTag().toString();
                    city = mTvCity.getTag() == null ? "" : mTvCity.getTag().toString();
                }
                YqSearchResultActivity.goActivity(this, mEtKeyword.getText().toString(), from, to, mEtSource.getText().toString(), region, city);
                break;
        }
    }


    private void showTimeSelectorView(int type) {
        DateTimePicker picker = new DateTimePicker(this, DateTimePicker.HOUR_24);//24小时值
        picker.setDateRangeStart(1910, 1, 1);//日期起点
        picker.setDateRangeEnd(2099, 1, 1);//日期终点
        picker.setTimeRangeStart(0, 0);//时间范围起点
        picker.setTimeRangeEnd(23, 59);//时间范围终点
        picker.setTextColor(getResources().getColor(R.color.color_0d7dff), getResources().getColor(R.color.color_666666));
        picker.setCancelTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setSubmitTextColor(getResources().getColor(R.color.color_0d7dff));
        picker.setLineColor(getResources().getColor(R.color.color_0d7dff));
        picker.setOnDateTimePickListener((DateTimePicker.OnYearMonthDayTimePickListener) (year, month, day, hour, minute) -> {
            //year:年，month:月，day:日，hour:时，minute:分
            String time = year + "-" + month + "-" + day + " "
                    + hour + ":" + minute;
            switch (type) {
                case 0:
                    mTvStartTime.setText(time);
                    break;
                case 1:
                    mTvEndTime.setText(time);
                    break;
            }
        });
        picker.show();
    }
}
